#include "Buffer.h"
#include <cstddef>
#include <cstring> // for memcpy
#include <vector>

namespace GiSo {



Buffer::Buffer()
{
}

Buffer::~Buffer()
{
}

const size_t Buffer::s_InitialSize;

bool Buffer::Append(const void* data, size_t len)
{
    if (data == nullptr || len == 0) return true;
    // std::unique_lock<std::shared_mutex> lock(m_Mutex); // 获取写锁
    if(m_Buffer.size() + len > s_InitialSize) {
        return false;
    }
    m_Buffer.insert(m_Buffer.end(), static_cast<const char*>(data), static_cast<const char*>(data) + len);
    return true;
}

bool Buffer::Append(const std::string& str)
{
    return Append(str.data(), str.size());
}

void Buffer::PopFront(size_t len)
{
    if (len == 0) return;
    // std::unique_lock<std::shared_mutex> lock(m_Mutex); // 获取写锁
    if (len > m_Buffer.size()) {
        len = m_Buffer.size(); // 防止弹出超过 Buffer 大小的数据
    }
    if (len > 0) {
        m_Buffer.erase(m_Buffer.begin(), m_Buffer.begin() + len);
    }
}

std::vector<char> Buffer::CopyToVector() const
{
    std::vector<char> out;
    out.assign(m_Buffer.begin(), m_Buffer.end()); // 使用 assign 避免不必要的内存分配
    return out;
}

std::string Buffer::CopyToString() const
{
    std::string out;
    out.assign(m_Buffer.begin(), m_Buffer.end()); // string 的 assign 也可以从迭代器范围赋值
    return out;
}

void Buffer::AssignToString(std::string& str) const
{
    str.assign(m_Buffer.begin(), m_Buffer.end());
}

void Buffer::Clear()
{
    m_Buffer.clear();
}

size_t Buffer::ReadableBytes() const
{
    return m_Buffer.size();
}

size_t Buffer::WritableBytes() const
{
    return s_InitialSize - m_Buffer.size(); //  deque 理论最大容量 - 当前大小， 简化表示
}

bool Buffer::isEmpty() const
{
    return m_Buffer.empty();
}

}